package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

@Component
@Slf4j
public class RedisCacheUtil {


    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //将任意java对象序列化为json并存储在string类型的key中，并且可以设置TTL过期时间
    public void setOne(String key,Object Object,Long time, TimeUnit unit){
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(Object), time, unit);
    }

    //将任意java对象序列化为json并存储在string类型的key中，并且可以设置逻辑过期时间，避免缓存击穿
    public void setTwo(String key,Object Object,Long time, TimeUnit unit){
        RedisData redisData = new RedisData();
        redisData.setData(Object);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }



    public <T,ID> T HuanCunChuanTou(String KeyPrefix, ID id, Class<T> type, Function<ID,T> dbFallback, Long time, TimeUnit unit){
        //获取key
        String key = KeyPrefix + id;
        //首先根据key获取值
        String json = stringRedisTemplate.opsForValue().get(key);
        //判断是否为空
        if(StrUtil.isNotBlank(json)){
           return JSONUtil.toBean(json, type);
        }
        if(json != null){
           return null;
        }
        //查询数据库
        T t = dbFallback.apply(id);
        //判断是否为空
        if(t == null){
            stringRedisTemplate.opsForValue().set(key, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        //存在，写入redis
        this.setOne(key, t, time, unit);

        return t;
    }



    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    public <T,ID> T HuanCunJiChuan(String KeyPrefix, ID id, Class<T> type, Function<ID,T> dbFallback, Long time, TimeUnit unit){
        String key= KeyPrefix + id;
        //根据key获取值
        String json = stringRedisTemplate.opsForValue().get(key);
        //判断是否为空
        if(StrUtil.isBlank(json)){
            //未命中 返回null
            return null;
        }
        //命中 需要先把json对象反序列化为java对象
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        T t=JSONUtil.toBean((JSONObject) redisData.getData(), type);
        LocalDateTime expireTime = redisData.getExpireTime();
        //判断是否逻辑过期
        if(expireTime.isAfter(LocalDateTime.now())){
            //未过期 返回
            return t;
        }
        //过期 需要缓存重建
        //获取互斥锁
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(lockKey);
        //判断是否获取锁成功
        if(isLock){
            //获取锁成功
            //开启独立线程，实现缓存重建
            CACHE_REBUILD_EXECUTOR.submit(()->{
                try{
                    //查询数据库
                    T t1 = dbFallback.apply(id);
                    //写入redis
                    this.setTwo(key, t1, time, unit);
                }catch (Exception e){
                    throw new RuntimeException(e);
                }finally {
                    unLock(lockKey);
                }
            });
        }
            return t;
    }

    //获取锁
    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }
    //释放锁
    private void unLock(String key){
        stringRedisTemplate.delete(key);
    }
}
